package serviceswarm

import (
	"context"
	"encoding/json"
	"github.com/aberic/gnomon"
	"github.com/aberic/proc"
	"github.com/pkg/errors"
	"google.golang.org/grpc"
	"gykjgit.dccnet.com.cn/chain/proto/swarm"
)

// ProcResources ProcResources
func ProcResources(url string) (map[string]*proc.Proc, error) {
	var m map[string]*proc.Proc
	resp, err := gnomon.GRPCRequestPools(url, func(conn *grpc.ClientConn) (i interface{}, err error) {
		// 创建grpc客户端
		cli := swarm.NewProcServerClient(conn)
		//客户端向grpc服务端发起请求
		return cli.Resources(context.Background(), &swarm.ReqResources{})
	})
	if nil == err {
		if response, ok := resp.(*swarm.RespResources); ok {
			if err = json.Unmarshal(response.Resources, &m); nil == err {
				return m, nil
			}
			return nil, errors.Wrap(err, "proc resources failed")
		}
		return nil, errors.New("proc resources failed, can not tarns interface to response")
	}
	return nil, errors.Wrap(err, "proc resources failed")
}
